# coding=utf-8

from flask import Blueprint, request, jsonify, json, make_response, redirect, g
from common.models.Customer import Customer
from common.models.Order import Order
from common.libs.user.UserLibs import UserLibs
from common.libs.Helper import ops_render, get_current_date, create_pages
from common.libs.UrlManager import UrlManager
from sqlalchemy import or_
from application import app,db
from web.controllers.BaseControllerHelper import *
from .Helper import *

route_customer = Blueprint( 'customer_page', __name__ )


@route_customer.route( "/index", methods=["GET"])
def index():
    """
    列表页
    :return:
    """
    context = {}
    req = request.values
    query, pages, offset, limit = create_pages(10, Customer.query, request)
    if 'mix_kw' in req:
        query = query.filter(Customer.nickname.ilike("%{0}%".format(req['mix_kw'])))

    if 'sex' in req and int(req['sex']) > -1:
        query = query.filter(Customer.sex == int(req['sex']))
    list = query.order_by(Customer.id.desc()).all()[offset:limit]
    context["list"] = list
    context["pages"] = pages
    context['search_con'] = req
    return ops_render("/customer/index.html", context=context)

@route_customer.route( "/info" , methods=["GET"])
def info() :
    """
    详细信息
    :return:
    """
    context = {}
    redirect_url = UrlManager.buildUrl("/customer/index")
    req = request.args
    id = int(req.get("id", 0))
    if id < 1:
        return redirect(redirect_url)
    customer_info = Customer.query.filter_by(id=id).first()
    if not customer_info:
        return redirect(redirect_url)

    shop_id = g.current_user.shop_id
    query, pages, offset, limit = create_pages(10, Order.query.filter_by(shop_id=shop_id, c_id=customer_info.id), request)
    order_list = query.order_by(Order.created_time.desc()).all()[offset:limit]
    context["customer_info"] = customer_info
    context["order_list"] = order_list
    context["pages"] = pages
    return ops_render("/customer/info.html", context=context)